﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SharpNetwork;
using SharpNetwork.SimpleWebSocket;

namespace SharpBroadcast
{
    public class WebSocketServerWrapper
    {
        public Server ServerProxy { get; private set; }

        public WebSocketServerWrapper(IMediaServer server)
        {
            ServerProxy = new Server();
            ServerProxy.SetIoBufferSize(1 * 1024);
            ServerProxy.SetIoFilter(new MessageCodec());
            ServerProxy.SetIoHandler(new ServerNetworkEventHandler(new MessageDispatcher(), server));
        }
    }

    public class ServerNetworkEventHandler : NetworkEventHandler
    {
        IMediaServer m_MediaServer = null;

        public ServerNetworkEventHandler(MessageDispatcher dispatcher, IMediaServer mediaServer)
            : base(dispatcher)
        {
            m_MediaServer = mediaServer;
        }

        public override void OnConnect(Session session)
        {
            base.OnConnect(session);

            session.SetMaxMessageQueueSize(0, m_MediaServer.OutputQueueSize);
        }

        public override void OnHandshake(Session session)
        {
            base.OnHandshake(session);

            if (m_MediaServer.IsWorking()) m_MediaServer.ValidateClient(session);
        }

        public override void OnDisconnect(Session session)
        {
            if (m_MediaServer.IsWorking()) m_MediaServer.RemoveClient(session);

            base.OnDisconnect(session);
        }

        public override void OnError(Session session, int errortype, string errormsg)
        {
            base.OnError(session, errortype, errormsg);

            if (errormsg != null && errormsg.Length > 0)
                m_MediaServer.Logger.Error(errormsg);
        }

    }
}
